package com.haople.test.trace;

import java.util.concurrent.CyclicBarrier;

import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;

import com.haople.test.trace.document.DocumentParser;
import com.haople.test.trace.document.HttpClientDocumentParserImpl;
import com.haople.test.trace.document.HttpUnitDocumentParserImpl;


/**
 * 需要加入 依赖包 
 * <dependency>
			<groupId>commons-cli</groupId>
			<artifactId>commons-cli</artifactId>
			<version>1.3.1</version>
		</dependency>
 * @author Administrator
 *
 */
public class Cli {

	private static final Options options = new Options(); 
	private static final DocumentParser httpDocumentParser=new HttpClientDocumentParserImpl();
	private static final DocumentParser httpUnitDocumentParser=new HttpUnitDocumentParserImpl();
	 
	 static{
		 /**
		  * 第一个参数 命令的简写； 第二个参数命令 命令的全写； 第三参数表示是否有参数； 第四个参数 代表 参数的说明
		  */
		// 添加 -h 参数
		 options.addOption("h", "help",false, "The command help"); 
		 options.addOption("b", "http",true, "input url and crawl by http"); 
		 options.addOption("t", "httpUnit",true, "input url and crawl by httpUnit"); 
		 options.addOption("n", "num",true, "input request nums"); 
	 }
	 
	 public static void help(){
		 /**
		  * 打印命令帮助提示
		  */
		 HelpFormatter hf = new HelpFormatter();
		 hf.printHelp("help info", options);
	 }
	 
	 public static void crawlByHttp(String url,Integer num){
		 try {
			 CyclicBarrier cyclicBarrier=new CyclicBarrier(num);
			 for(int i=0;i<num;i++){
				 new Thread(new Fuck(httpDocumentParser, url,cyclicBarrier)).start();
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }
	 
	 public static void crawlByHttpUnit(String url,Integer num){
		 try {
			 CyclicBarrier cyclicBarrier=new CyclicBarrier(num);
			 for(int i=0;i<num;i++){
				 new Thread(new Fuck(httpUnitDocumentParser, url,cyclicBarrier)).start();
			 }
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 }
	 
	 public static Options getOptions(){
		 return options;
	 }
	 
}

class Fuck implements Runnable{
	private final DocumentParser documentParser;
	private final String url;
	private CyclicBarrier cyclicBarrier;
	public Fuck(final DocumentParser documentParser,final String url,CyclicBarrier cyclicBarrier) {
		this.documentParser=documentParser;
		this.url=url;
		this.cyclicBarrier=cyclicBarrier;
	}
	public void run() {
		try {
			cyclicBarrier.await();
			System.err.println("-------------------------"+Thread.currentThread().getName()+"-----开始执行-----");
			String html=documentParser.getContent(url);
			System.out.println(html);
			cyclicBarrier.await();
			System.err.println("-------------------------"+Thread.currentThread().getName()+"-----执行完毕-----");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
}

